package com.orangelife.mobile.pay.biz;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.common.sp.ShoppingSp;
import com.common.sp.UserSp;
import com.curry.android.util.TimeUtil;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.pay.activity.UsersPaidActivity;
import com.orangelife.mobile.pay.interfaze.IPayCallBack;
import com.orangelife.mobile.pay.interfaze.IPayManage;
import com.orangelife.mobile.util.ToastHelper;
import com.thirdsdk.yintong.pay.utils.BaseHelper;
import com.thirdsdk.yintong.pay.utils.Constants;
import com.thirdsdk.yintong.pay.utils.MobileSecurePayer;
import com.thirdsdk.yintong.pay.utils.PayOrder;
import com.thirdsdk.yintong.pay.utils.Rsa;

/**
 * 连连支付实现类
 */
public class LianLianManageImpl implements IPayManage {
    private static final int RQF_PAY = 3;
    private IPayCallBack iPayCallBack;

    public LianLianManageImpl(IPayCallBack iPayCallBack) {
        this.iPayCallBack = iPayCallBack;
    }

    @Override
    public void getOuttradenoFromServer(String orderID, int type) {
    }

    @Override
    public void setParameter(Context context, JSONObject jsonObject) {
        SimpleDateFormat dataFormat = new SimpleDateFormat(
                "yyyyMMddHHmmss");
        Date date = new Date();
        String timeString = dataFormat.format(date);
        PayOrder order = new PayOrder();
        try {
            order.setBusi_partner("109001");
            order.setNo_order(jsonObject.getString("outtradeno"));
            order.setDt_order(timeString);
            order.setName_goods(jsonObject.getString("goodName"));
            order.setNotify_url(jsonObject.getString("appNotifyUrl"));
            //  MD5 签名方式
//			order.setSign_type(PayOrder.SIGN_TYPE_MD5);
            //  RSA 签名方式
            order.setSign_type(PayOrder.SIGN_TYPE_RSA);
            order.setValid_order("10080");
            order.setUser_id(UserSp.getLoginID());
            // order.setId_no("");
            // order.setAcct_name("");
//			order.setMoney_order("0.01");
            order.setMoney_order(jsonObject.getString("totalCost"));
            // 风险控制参数
            String phone = ShoppingSp.getTradePhone();
            order.setRisk_item(constructRiskItem(phone));
            String sign = "";
            order.setOid_partner(jsonObject.getString("OID_PARTNER"));
//			order.setOid_partner("201309252000003521");
            String content = BaseHelper.sortParam(order);
            //  MD5 签名方式, 签名方式包括两种，一种是MD5，一种是RSA 这个在商户站管理里有对验签方式和签名Key的配置。
//			sign = Md5Algorithm.getInstance().sign(content,
//					jsonObject.getString("MD5_KEY"));
//			sign = Md5Algorithm.getInstance().sign(content,
//					"md5key_52game_0926");
            // RSA 签名方式
            sign = Rsa.sign(content, jsonObject.getString("TRADER_PRI_KEY"));
//			sign = Rsa.sign(content,EnvConstants.RSA_PRIVATE);
            order.setSign(sign);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String content4Pay = BaseHelper.toJSONString(order);
        // 关键 content4Pay 用于提交到支付SDK的订单支付串，如遇到签名错误的情况，请将该信息帖给我们的技术支持
        Log.i(PayManageImpl.class.getSimpleName(), content4Pay);
        MobileSecurePayer msp = new MobileSecurePayer();
        msp.pay(content4Pay, handler, RQF_PAY,
                (UsersPaidActivity) context, false);
    }

    private String constructRiskItem(String phone) {
        JSONObject mRiskItem = new JSONObject();
        try {
            mRiskItem.put("user_info_mercht_userno", UserSp.getLoginID());
            long regTime = 0;
            try {
                regTime = Long.parseLong(String.valueOf(UserSp.getRegisterTime()));
            } catch (NumberFormatException e) {
                Log.e(LianLianManageImpl.class.getSimpleName(), e.getMessage());
                e.printStackTrace();
            }
            mRiskItem.put("user_info_dt_register", TimeUtil.timeStampToDate(regTime, "yyyyMMddHHmmss"));
            mRiskItem.put("frms_ware_category", "4999");
            mRiskItem.put("delivery_phone", phone);
            mRiskItem.put("delivery_addr_province", ShoppingSp.getProvinceCode());/*省级编码，目前写死福建，原来是SP，但是写这个的人压根没调set方法*/
            mRiskItem.put("delivery_addr_city", ShoppingSp.getCityCode());/*市级编码，同上*/
            mRiskItem.put("logistics_mode", "2");
            mRiskItem.put("delivery_cycle", "Other");
//			mRiskItem.put("request_imei", "1122111221");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return mRiskItem.toString();
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RQF_PAY:
                    JSONObject objContent = BaseHelper.string2JSON((String) msg.obj);
                    String retCode = objContent.optString("ret_code");
                    String retMsg = objContent.optString("ret_msg");
                    // 成功
                    if (Constants.RET_CODE_SUCCESS.equals(retCode)) {
//              	  ToastHelper.getInstance()._toast(
//                            "支付成功，交易状态码：" + retCode);
                        iPayCallBack.success();
                    } else if (Constants.RET_CODE_PROCESS.equals(retCode)) {
                        String resulPay = objContent.optString("result_pay");
                        if (Constants.RESULT_PAY_PROCESSING
                                .equalsIgnoreCase(resulPay)) {
//                  	  ToastHelper.getInstance()._toast(
//                  			  objContent.optString("ret_msg") + "交易状态码："
//                                        + retCode);
                            iPayCallBack.handling();
                        }
                    } else {
                        //  失败
//              	  ToastHelper.getInstance()._toast(retMsg+
//                            "，交易状态码：" + retCode);
                        iPayCallBack.fail();
                    }
                    Log.e("retCode=", retCode);
                    Log.e("retMsg=", retMsg);
                    break;
                case Constant.WHAT_EXPIRE_ORDER:
                    ToastHelper.getInstance()._toast(msg.obj.toString());
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void newPay(final Context context,JSONObject jsonObject){};
}
